import '../services/api_service.dart';
import '../models/base_model.dart';
import '../models/auth_model.dart';
import '../models/calendar_model.dart';
/// API仓库层 - API Repository Layer
/// 负责处理所有业务接口调用和数据处理逻辑
/// 将API响应转换为应用程序可用的数据模型
class ApiRepository {
  final ApiService _apiService = ApiService.to;

  // ==================== 认证相关接口 - Authentication APIs ====================

  /// 请求短信验证码 - Request SMS verification code
  /// @param phone 手机号码
  /// @return Future<BaseResponse<String>> 包含验证码发送结果的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<String>> requestSmsCode(String phone) async {
    try {
      final response = await _apiService.post('/auth/sms-code', data: {'phone': phone});
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json.toString());
      } else {
        return BaseResponse.error(message: '发送短信验证码失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '请求短信验证码失败: ${e.toString()}');
    }
  }

  /// 请求邮箱验证码 - Request email verification code
  /// @param email 邮箱地址
  /// @return Future<BaseResponse<String>> 包含验证码发送结果的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<String>> requestEmailCode(String email) async {
    try {
      final response = await _apiService.post('/auth/email-code', data: {'email': email});
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json.toString());
      } else {
        return BaseResponse.error(message: '发送邮箱验证码失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '请求邮箱验证码失败: ${e.toString()}');
    }
  }

  /// 用户注册 - User registration
  /// @param request 注册请求数据
  /// @return Future<BaseResponse<AuthUser>> 包含注册用户信息的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<AuthUser>> register(RegisterRequest request) async {
    try {
      if (!request.isValid) {
        return BaseResponse.error(message: '注册信息不完整');
      }

      final response = await _apiService.post('/auth/register', data: request.toJson());
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(
          data, 
          (json) => AuthUser.fromJson(json as Map<String, dynamic>),
        );
      } else {
        return BaseResponse.error(message: '用户注册失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '用户注册失败: ${e.toString()}');
    }
  }

  /// 用户登录 - User login
  /// @param request 登录请求数据
  /// @return Future<BaseResponse<AuthUser>> 包含登录用户信息的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<AuthUser>> login(LoginRequest request) async {
    try {
      if (!request.isValid) {
        return BaseResponse.error(message: '登录信息不完整');
      }

      final response = await _apiService.post('/auth/login', data: request.toJson());
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        final authUser = AuthUser.fromJson(data['data'] as Map<String, dynamic>);
        
        // 设置认证令牌 - Set authentication token
        _apiService.setAuthToken(authUser.token);
        
        return BaseResponse.success(data: authUser, message: '登录成功');
      } else {
        return BaseResponse.error(message: '用户登录失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '用户登录失败: ${e.toString()}');
    }
  }

  // ==================== 万年历相关接口 - Calendar APIs ====================

  /// 获取万年历信息 - Get calendar information
  /// @param dateString 日期字符串 (格式: YYYY-MM-DD)
  /// @return Future<BaseResponse<CalendarInfo>> 包含万年历信息的响应
  /// 注意：此方法目前使用模拟数据，实际项目中应调用真实API
  Future<BaseResponse<CalendarInfo>> getCalendarInfo(String dateString) async {
    try {
      // 模拟API响应延迟 - Simulate API response delay
      await Future.delayed(const Duration(milliseconds: 300));

      // 创建模拟万年历数据 - Create mock calendar data
      final calendarInfo = CalendarInfo.defaultInstance();
      
      return BaseResponse.success(
        data: calendarInfo,
        message: '获取万年历信息成功',
      );
    } catch (e) {
      return BaseResponse.error(message: '获取万年历信息失败: ${e.toString()}');
    }
  }

  /// 获取月份万年历数据 - Get month calendar data
  /// @param year 年份
  /// @param month 月份
  /// @return Future<BaseResponse<MonthCalendarData>> 包含月份万年历数据的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<MonthCalendarData>> getMonthCalendarData({
    required int year,
    required int month,
  }) async {
    try {
      final response = await _apiService.get(
        '/calendar/month',
        queryParameters: {
          'year': year,
          'month': month,
        },
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(
          data,
          (json) => MonthCalendarData.fromJson(json as Map<String, dynamic>),
        );
      } else {
        return BaseResponse.error(message: '获取月份万年历数据失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取月份万年历数据失败: ${e.toString()}');
    }
  }

  // ==================== 运势相关接口 - Fortune APIs ====================
  // 注意：根据用户要求，运势相关功能将被替换为老黄历功能

  /// 获取每日运势 - Get daily fortune
  /// @param date 日期字符串 YYYY-MM-DD
  /// @return Future<BaseResponse<Map<String, dynamic>>> 包含每日运势的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<Map<String, dynamic>>> getDailyFortune(String date) async {
    try {
      final response = await _apiService.get(
        '/fortune/daily',
        queryParameters: {
          'date': date,
        },
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as Map<String, dynamic>);
      } else {
        return BaseResponse.error(message: '获取每日运势失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取每日运势失败: ${e.toString()}');
    }
  }

  /// 获取生肖运势 - Get zodiac fortune
  /// @param zodiac 生肖名称
  /// @param date 目标日期，默认为当前日期
  /// @return Future<BaseResponse<Map<String, dynamic>>> 包含生肖运势的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<Map<String, dynamic>>> getZodiacFortune(
    String zodiac, {
    DateTime? date,
  }) async {
    try {
      final targetDate = date ?? DateTime.now();
      final response = await _apiService.get(
        '/calendar/fortune/zodiac',
        queryParameters: {
          'zodiac': zodiac,
          'year': targetDate.year,
          'month': targetDate.month,
          'day': targetDate.day,
        },
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as Map<String, dynamic>);
      } else {
        return BaseResponse.error(message: '获取生肖运势失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取生肖运势失败: ${e.toString()}');
    }
  }

  /// 获取星座运势 - Get constellation fortune
  /// @param constellation 星座名称
  /// @param date 目标日期，默认为当前日期
  /// @return Future<BaseResponse<Map<String, dynamic>>> 包含星座运势的响应
  /// @throws ApiException 当请求失败时抛出
  Future<BaseResponse<Map<String, dynamic>>> getConstellationFortune(
    String constellation, {
    DateTime? date,
  }) async {
    try {
      final targetDate = date ?? DateTime.now();
      final response = await _apiService.get(
        '/fortune/constellation',
        queryParameters: {
          'constellation': constellation,
          'year': targetDate.year,
          'month': targetDate.month,
          'day': targetDate.day,
        },
      );

      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as Map<String, dynamic>);
      } else {
        return BaseResponse.error(message: '获取星座运势失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取星座运势失败: ${e.toString()}');
    }
  }

  // ==================== 工具方法 - Utility Methods ====================

  /// 设置认证令牌 - Set authentication token
  /// @param token 认证令牌
  void setAuthToken(String token) {
    _apiService.setAuthToken(token);
  }

  /// 清除认证令牌 - Clear authentication token
  void clearAuthToken() {
    _apiService.clearAuthToken();
  }

  /// 检查网络连接状态 - Check network connection status
  /// @return Future<bool> 连接状态，true表示连接正常
  Future<bool> checkConnection() async {
    return await _apiService.checkConnection();
  }

  /// 取消所有请求 - Cancel all requests
  void cancelAllRequests() {
    _apiService.cancelRequests();
  }

  // ==================== 商品相关接口 - Product APIs ====================

  /// 获取商品分类 - Get product categories
  /// @return Future<BaseResponse<List<dynamic>>> 包含商品分类列表的响应
  Future<BaseResponse<List<dynamic>>> getProductCategories() async {
    try {
      final response = await _apiService.get('/products/categories');
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as List<dynamic>);
      } else {
        return BaseResponse.error(message: '获取商品分类失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取商品分类失败: ${e.toString()}');
    }
  }

  /// 获取推荐商品 - Get featured products
  /// @return Future<BaseResponse<List<dynamic>>> 包含推荐商品列表的响应
  Future<BaseResponse<List<dynamic>>> getFeaturedProducts() async {
    try {
      final response = await _apiService.get('/products/featured');
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as List<dynamic>);
      } else {
        return BaseResponse.error(message: '获取推荐商品失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取推荐商品失败: ${e.toString()}');
    }
  }

  /// 根据分类获取商品 - Get products by category
  /// @param categoryId 分类ID
  /// @return Future<BaseResponse<List<dynamic>>> 包含商品列表的响应
  Future<BaseResponse<List<dynamic>>> getProductsByCategory(String categoryId) async {
    try {
      final response = await _apiService.get('/products/category/$categoryId');
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as List<dynamic>);
      } else {
        return BaseResponse.error(message: '获取分类商品失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '获取分类商品失败: ${e.toString()}');
    }
  }

  /// 添加商品到购物车 - Add product to cart
  /// @param productId 商品ID
  /// @param quantity 数量
  /// @return Future<BaseResponse<Map<String, dynamic>>> 包含添加结果的响应
  Future<BaseResponse<Map<String, dynamic>>> addToCart(String productId, int quantity) async {
    try {
      final response = await _apiService.post('/cart/add', data: {
        'product_id': productId,
        'quantity': quantity,
      });
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as Map<String, dynamic>);
      } else {
        return BaseResponse.error(message: '添加到购物车失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '添加到购物车失败: ${e.toString()}');
    }
  }

  /// 购买商品 - Purchase product
  /// @param productId 商品ID
  /// @return Future<BaseResponse<Map<String, dynamic>>> 包含购买结果的响应
  Future<BaseResponse<Map<String, dynamic>>> purchaseProduct(String productId) async {
    try {
      final response = await _apiService.post('/products/purchase', data: {
        'product_id': productId,
      });
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as Map<String, dynamic>);
      } else {
        return BaseResponse.error(message: '购买商品失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '购买商品失败: ${e.toString()}');
    }
  }

  /// 搜索商品 - Search products
  /// @param keyword 搜索关键词
  /// @return Future<BaseResponse<List<dynamic>>> 包含搜索结果的响应
  Future<BaseResponse<List<dynamic>>> searchProducts(String keyword) async {
    try {
      final response = await _apiService.get('/products/search', queryParameters: {
        'keyword': keyword,
      });
      
      if (response.statusCode == 200 && response.data != null) {
        final data = response.data as Map<String, dynamic>;
        return BaseResponse.fromJson(data, (json) => json as List<dynamic>);
      } else {
        return BaseResponse.error(message: '搜索商品失败');
      }
    } on ApiException catch (e) {
      return BaseResponse.error(message: e.message, code: e.statusCode);
    } catch (e) {
      return BaseResponse.error(message: '搜索商品失败: ${e.toString()}');
    }
  }
}